package com.binguo.common.paymodel;


import com.binguo.common.sms.JacksonUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import java.util.concurrent.TimeUnit;

//@Component
public class WeixinTokenRefreshService {

//    @PostConstruct
    public void refresh() throws Exception{
        String expires_in = handler();

        if (expires_in == null) {
            return;
        }

        ThreadManager.scheduledThreadPoolExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    handler();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, Integer.valueOf(expires_in), Integer.valueOf(expires_in), TimeUnit.SECONDS);

    }

    public String handler() throws Exception{
        HttpGet httpPost = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + WeixinConfig.appId + "&secret=" + WeixinConfig.secret);

        CloseableHttpResponse closeableHttpResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
        String tokenResponce = EntityUtils.toString(closeableHttpResponse.getEntity());

        try{

            System.out.println("getToken response:" + tokenResponce);
            WXToken wxToken = JacksonUtil.json2Bean(tokenResponce, WXToken.class);
            String token = wxToken.getAccess_token();
            WeixinConfig.setAccessToken(token);

            HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi");

            closeableHttpResponse = HttpConnectionManager.getHttpClient().execute(httpGet);
            String ticketResponce = EntityUtils.toString(closeableHttpResponse.getEntity());


            WXTicket wxTicket = JacksonUtil.json2Bean(ticketResponce, WXTicket.class);
            WeixinConfig.setJsapiTicket(wxTicket.getTicket());

            return wxToken.getExpires_in();
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
